import type { RouteRecordRaw } from 'vue-router'
import { defineStore } from 'pinia'
import { asyncRoutes, constantRoutes } from '@/router'

/**
 * 路由是否有某个角色
 * @param roles
 * @param route
 */
function hasPermission(roles: string[], route: RouteRecordRaw) {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => {
      if (route.meta?.roles) {
        return route.meta.roles.includes(role)
      }
      return false
    })
  } else {
    return true
  }
}

/**
 * 根据角色过滤动态路由
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes: RouteRecordRaw[], roles: string[]) {
  const res: RouteRecordRaw[] = []
  routes.forEach((route) => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

// setup
export const usePermissionStore = defineStore('permission', () => {
  // state
  const routes = ref<any>([])

  // actions
  function setRoutes(newRoutes: any[]) {
    routes.value = constantRoutes.concat(newRoutes)
  }
  /**
   * 生成动态路由
   *
   * @param roles 用户角色集合
   * @returns
   */
  function generateRoutes(roles: string[]) {
    return new Promise<RouteRecordRaw[]>((resolve) => {
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      setRoutes(accessedRoutes)
      resolve(accessedRoutes)
    })
  }

  return { routes, setRoutes, generateRoutes }
})
